<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-align="right"
    label-width="100"
    size="default"
    class="pr-6"
    label-position="top"
  >
    <div class="flex items-center py-2" v-if="type == 'default'">
      <span class="mr-2">推荐平台/站点</span>
      <SelectPlatformSite
        v-model:platform="form.platform_id"
        v-model:site="form.site_text"
        @changePlatform="changePlatform"
        @changeSiteInfo="changeSite"
      >
      </SelectPlatformSite>
      <span class="ml-2">国家：</span>
      <SelectCountryCurrency
        v-model="form.site_country_code"
        valueKey="country"
        placeholder="国家"
        @change="changeCountryCurrency"
      ></SelectCountryCurrency>
    </div>

    <el-card class="box-card mb-4 box-card-style" shadow="never" v-if="type == 'default'">
      <el-row class="flex justify-center">
        <el-col :span="16">
          <div class="">
            <el-form-item prop="selling_price">
              <template #label>
                <span class="font-bold">建议销售价</span>
              </template>
              <el-input
                v-model.trim="form.selling_price"
                @input="limitInput($event, 'form', 'selling_price')"
                placeholder="请输入建议销售价"
                class="input-with-select custom-select-style"
                @blur="changePrice"
              >
                <template #append>
                  <SelectCurrency
                    class="!w-[150px]"
                    ref="SelectCurrencyRef"
                    v-model="form.currency_id"
                    placeholder="请选择币种"
                    @changeItem="changeCurrency"
                  ></SelectCurrency>
                </template>
              </el-input>
            </el-form-item>
            <div class="flex justify-between">
              <div>
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="含税价格"
                  placement="top"
                >
                  <div class="flex justify-start items-center text-gray-500 text-sm">
                    <svg-icon class="mr-1" icon-class="hint_line" />含税价格
                  </div>
                </el-tooltip>
              </div>
              <div class="flex justify-start items-center text-sm">
                <div v-if="form.currency_id && form.selling_price" class="mr-2">
                  销售价:{{ form.selling_price_rmb }} CNY
                </div>
                <div v-if="form.currency_id">汇率:{{ form.exchange_rate }}</div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col class="pl-6" :span="8">
          <div class="text-lg mt-6 flex items-center">
            预估产品毛利率:
            <span class="text-[#ff0000] text-lg"> {{ calculateProductGross(form) }}</span>
            %
            <el-tooltip placement="top">
              <template #content>
                <div v-html="PRODUCT_GROSS_MARGIN_DESCRIPTION"></div>
              </template>
              <svg-icon class="ml-2" icon-class="QuestionFilled"></svg-icon>
            </el-tooltip>
          </div>
          <div class="text-lg">
            预估销售毛利率:
            <span class="text-[#ff0000] text-lg">{{ calculateSaleGross(form) }}</span> %
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-row :gutter="20">
      <el-col :span="6" v-if="type == 'default'">
        <el-form-item label="采购成本" prop="purchase_cost">
          <el-input
            v-model.trim="form.purchase_cost"
            @input="limitInput($event, 'form', 'purchase_cost')"
            placeholder="输入"
            class="input-with-select"
          >
            <template #append>
              <el-button type="primary" class="suffix-unit">CNY</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6" v-if="type == 'default'">
        <el-form-item label="单品毛重" prop="gross_weight_g">
          <el-input
            v-model.trim="form.gross_weight_g"
            placeholder="输入"
            @input="limitInput($event, 'form', 'gross_weight_g')"
          >
            <template #append>
              <el-button type="primary" class="suffix-unit">g</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6" class="relative" v-if="type == 'operationAudit'">
        <div v-if="form.selling_price_rmb" class="absolute right-3">
          兑人民币:{{ form.selling_price_rmb }} CNY
        </div>
        <el-form-item label="建议售价" required>
          <el-input
            v-model.trim="form.selling_price"
            @input="limitInput($event, 'form', 'selling_price')"
            placeholder="请输入建议销售价"
            class="input-with-select custom-select-style"
            @blur="changePrice"
            :disabled="disabled"
          >
            <template #append>
              <SelectCurrency
                class="!w-[100px]"
                ref="SelectCurrencyRef"
                v-model="form.currency_id"
                placeholder="请选择币种"
                @changeItem="changeCurrency"
                :disabled="disabled"
              ></SelectCurrency>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6" v-if="type == 'default'">
        <el-form-item label="包装尺寸" required>
          <div class="size-box">
            <el-form-item prop="packing_specification.length">
              <el-input
                class="radius-right-0"
                placeholder="长"
                v-model="form.packing_specification.length"
                @input="limitInput($event, 'packing_specification', 'length')"
              />
            </el-form-item>
            <el-form-item prop="packing_specification.width">
              <el-input
                class="radius-left-0 radius-right-0"
                style="margin-left: -1px"
                v-model="form.packing_specification.width"
                placeholder="宽"
                @input="limitInput($event, 'packing_specification', 'width')"
              />
            </el-form-item>

            <el-form-item prop="packing_specification.height">
              <el-input
                class="radius-left-0"
                style="margin-left: -1px"
                placeholder="高"
                v-model="form.packing_specification.height"
                @input="limitInput($event, 'packing_specification', 'height')"
              />
            </el-form-item>

            <div class="size-unit">cm</div>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="6" v-if="type == 'default'">
        <el-form-item
          label="运营人员"
          :prop="form.is_operation_check ? 'operation_user_id' : ''"
        >
          <select-personnel
            class="w-full"
            v-model="form.operation_user_id"
            placeholder="请选择运营人员"
            @changeName="changePerson"
          ></select-personnel>
        </el-form-item>
      </el-col>

      <el-col :span="6" class="relative">
        <div v-if="form.commission_rate" class="absolute right-3">
          平台佣金 {{ form.platform_fee }} CNY
        </div>
        <el-form-item label="佣金比例">
          <el-input
            :disabled="!(form.selling_price && form.currency_id) || disabled"
            v-model.trim="form.commission_rate"
            placeholder="请输入"
            @input="limitInput($event, 'form', 'commission_rate')"
            @blur="handlePlatform"
          >
            <template #append>
              <el-button type="primary" class="suffix-unit">%</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6" class="relative">
        <div v-if="form.other_fee" class="absolute right-3">
          其他费用

          {{ calculateOther(form) }}CNY
        </div>
        <el-form-item label="其他费用:">
          <el-input
            type="number"
            v-model.trim="form.other_fee"
            placeholder="请输入"
            @input="limitInput($event, 'form', 'fee')"
            @change="handleOther"
            clearable
            :disabled="disabled"
          >
            <template #append>
              <el-select
                v-model="form.other_fee_currency"
                placeholder="请选择"
                style="width: 80px"
                @change="handleOther('select')"
                :key="typeOptions[1] || 'typeOptions'"
                class="suffix-unit"
                :disabled="disabled"
              >
                <el-option
                  v-for="item in typeOptions"
                  :label="item"
                  :value="item"
                  :key="item"
                />
              </el-select>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="退款率">
          <el-input
            v-model.trim="form.refund_rate"
            placeholder="请输入"
            @input="limitInput($event, 'form', 'refund_rate')"
            :disabled="disabled"
          >
            <template #append>
              <el-button type="primary" class="suffix-unit">%</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="广告费比例">
          <el-input
            v-model.trim="form.advertising_rate"
            placeholder="请输入"
            @input="limitInput($event, 'form', 'advertising_rate')"
            :disabled="disabled"
          >
            <template #append>
              <el-button type="primary" class="suffix-unit">%</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6" class="relative">
        <div v-if="form.vat_tax" class="absolute right-3">
          VAT费用
          {{ calculateAgainstRMB(form.selling_price_rmb, form.vat_tax / 100) }} CNY
        </div>
        <el-form-item label="VAT税率">
          <el-input
            v-model.trim="form.vat_tax"
            placeholder="请输入"
            @blur="changeVAT"
            :disabled="disabled"
          >
            <template #append>
              <el-button type="primary" class="suffix-unit">%</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6" class="relative" v-if="form.platform_code == 'amazon'">
        <div v-if="form.fba_cost" class="absolute right-3">
          {{ calculateAgainstRMB(form.fba_cost, form.exchange_rate) }} CNY
        </div>
        <el-form-item label="FBA操作费">
          <el-input
            v-model.trim="form.fba_cost"
            placeholder="请输入"
            oninput="value=value.replace(/[^0-9]/g,'')"
            :disabled="disabled"
          >
            <template #append>
              <el-button type="primary" class="suffix-unit">{{
                form.currency_name
              }}</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6" v-else>
        <el-form-item label="海外仓入库费">
          <el-input
            v-model.trim="form.oversea_into_cost"
            placeholder="请输入"
            oninput="value=value.replace(/[^0-9]/g,'')"
            :disabled="disabled"
          >
            <template #append>
              <el-button type="primary" class="suffix-unit">CNY</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="关税">
          <VGroup>
            <el-select
              v-model.trim="form.tariff_percent"
              filterable
              allow-create
              default-first-option
              :reserve-keyword="false"
              clearable
              placeholder="比例"
              style="width: 80px"
              @change="changePercent"
              :disabled="disabled"
            >
              <el-option
                v-for="item in tariffOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-input
              v-model.trim="form.tariff"
              @input="limitInput($event, 'form', 'tariff')"
              placeholder="关税"
              class="input-with-select"
              style="width: 140px"
              @blur="changeTariff()"
              :disabled="disabled"
            >
              <template #append>
                <el-button type="primary" class="suffix-unit">CNY</el-button>
              </template>
            </el-input>
          </VGroup>
        </el-form-item>
      </el-col>

      <el-col :span="6" class="relative">
        <div v-if="form.suggest_prepare_count" class="absolute right-3">
          备货金额:{{ calculateStockTotal(form) }}
          CNY
        </div>
        <el-form-item label="备货量">
          <el-input
            v-model.trim="form.suggest_prepare_count"
            placeholder="请输入"
            oninput="value=value.replace(/[^0-9]/g,'')"
            :disabled="disabled"
          >
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="目的仓">
          <SelectOverseasWarehouse
            class="w-full"
            v-model="form.destination_warehouse_id"
            placeholder="请选择目的仓"
            @change="changeDestinationWarehouse"
            :disabled="disabled"
          ></SelectOverseasWarehouse>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="预估产品等级">
          <el-select
            class="w-full"
            v-model="form.product_level"
            clearable
            @change="changeProductLevel"
            :disabled="disabled"
          >
            <el-option
              v-for="item in options['goods.GoodsSku']?.[0].productLevelText"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="头程">
          <div class="flex w-full">
            <el-select
              class="w-40 radius-right-0"
              v-model="form.head_channel_id"
              clearable
              placeholder="请选择运输方式"
              @change="changeHead"
              :disabled="disabled"
            >
              <el-option
                v-for="item in channel_options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <SelectChannel
              ref="selectChannelRef"
              v-model="form.head_logistic_channel_id"
              placeholder="请选择物流渠道"
              type="head"
              :transportType="form.head_channel_id"
              @change="changeChannel($event, 'head_logistic_channel')"
              @changeItem="changeChannelItem($event, 'head_channel_id')"
              :disabled="disabled"
            ></SelectChannel>
            <el-button
              type="primary"
              @click="handleTrialProfit(form.head_logistic_channel_id, 'head')"
              :disabled="disabled"
              >运费试算</el-button
            >
            <el-input
              v-model="form.head_time"
              style="width: 150px"
              placeholder="时效（天）"
              :disabled="disabled"
            ></el-input>
            <el-input
              style="margin-left: -1px"
              v-model.trim="form.head_freight"
              @input="limitInput($event, 'form', 'head_freight')"
              placeholder="预估运费"
              class="flex input-select flex-1 radius-left-0"
              oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,4}).*/,'$1')"
              :disabled="disabled"
            >
              <template #append>
                <el-button type="primary" class="suffix-unit">CNY</el-button>
              </template>
            </el-input>
            <el-button
              type="primary"
              @click="handleRecommendationChannel('head')"
              :disabled="disabled"
              >推荐渠道</el-button
            >
          </div>
        </el-form-item>
      </el-col>

      <el-col :span="24">
        <el-form-item label="尾程">
          <div class="flex w-full">
            <el-select
              class="w-40 radius-right-0"
              v-model="form.tail_channel_id"
              clearable
              placeholder="请选择运输方式"
              @change="changeTail"
              :disabled="disabled"
            >
              <el-option
                v-for="item in channel_options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <SelectChannel
              v-model="form.tail_logistic_channel_id"
              placeholder="请选择物流渠道"
              type="tail"
              :transportType="form.tail_channel_id"
              @change="changeChannel($event, 'tail_logistic_channel')"
              @changeItem="changeChannelItem($event, 'tail_channel_id')"
              :disabled="disabled"
            ></SelectChannel>
            <el-button
              type="primary"
              @click="handleTrialProfit((form.tail_logistic_channel_id, 'tail'))"
              :disabled="disabled"
              >运费试算</el-button
            >
            <el-input
              v-model="form.tail_time"
              style="width: 150px"
              placeholder="时效（天）"
              :disabled="disabled"
            ></el-input>
            <el-input
              style="margin-left: -1px"
              v-model.trim="form.tail_freight"
              @input="limitInput($event, 'form', 'tail_freight')"
              placeholder="预估运费"
              class="flex input-select flex-1 radius-left-0"
              oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,4}).*/,'$1')"
              :disabled="disabled"
            >
              <template #append>
                <el-button type="primary" class="suffix-unit">CNY</el-button>
              </template>
            </el-input>
            <el-button
              type="primary"
              @click="handleRecommendationChannel('tail')"
              :disabled="disabled"
              >推荐渠道</el-button
            >
          </div>
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item label="竞品链接">
      <div class="flex">
        <el-input
          class="!w-[800px]"
          v-model.trim="form.product_link"
          placeholder="请输入"
          :disabled="disabled"
        />
        <el-button type="primary" @click="copy(form.product_link)">复制</el-button>
        <el-button type="primary" @click="openLink(form.product_link)">跳转</el-button>
      </div>
    </el-form-item>
    <el-form-item label="备注">
      <el-input
        v-model="form.remark"
        :autosize="{ minRows: 4, maxRows: 10 }"
        placeholder="请输入"
        type="textarea"
        :disabled="disabled"
      />
    </el-form-item>
  </el-form>
  <RecommendationLogistics
    ref="RecommendationLogisticsRef"
    @checked="checkedLogistics"
  ></RecommendationLogistics>
</template>
<script setup>
import { nextTick, reactive, toRefs } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import api from "../../api";
import RecommendationLogistics from "@/components/RecommendationLogistics";
import SelectOverseasWarehouse from "@/components/Selects/SelectOverseasWarehouse/index.vue";
import SelectCountryCurrency from "@/components/Selects/SelectCountryCurrency";
import SelectPlatformSite from "@/components/SelectPlatformSite";
import SelectChannel from "@/components/SelectChannel";
import {
  tariffOptions,
  VATTaxRateOptions,
  PRODUCT_GROSS_MARGIN_DESCRIPTION,
} from "../../data.js";
import { openLink, copy } from "@/utils/index.js";
import { feeTrialCalcFreight } from "@/api/index.js";
import { channel_options } from "@/utils/data.js";
import useCommonStore from "@/store/modules/common";
import {
  calculateProductGross,
  calculateSaleGross,
  calculateAgainstRMB,
  calculateStockTotal,
} from "../../utils.js";
import SelectCurrency from "@/components/SelectCurrency";

let options = reactive(inject("options"));
const formData = reactive(inject("form"));

const commonStore = useCommonStore();
const platformOptions = computed(() => {
  if (!commonStore.platformOptions) {
    commonStore.getPlatformList();
  }
  return commonStore.platformOptions || [];
});

const props = defineProps({
  modelValue: { type: Object, default: () => ({}) },
  type: { type: String, default: "default" },
  disabled: { type: Boolean, default: false },
});

const { type, disabled } = toRefs(props);

const form = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  },
});

const validateDimension = (rule, value, callback) => {
  if (!/^\d+(\.\d+)?$/.test(value)) {
    callback(new Error("请输入有效的数字"));
  } else {
    callback();
  }
};

const data = reactive({
  packing_specification: {
    width: null,
    length: null,
    height: null,
  },
  formRef: null,
  currencyList: [],
  seleceOptions: [],
  typeOptions: ["%"],
  rules: {
    selling_price: [{ trigger: "blur", required: true, message: "请输入建议销售价" }],
    operation_user_id: [{ trigger: "change", required: true, message: "请选择运营人员" }],
    purchase_cost: [{ trigger: "blur", required: true, message: "请输入采购成本" }],
    gross_weight_g: [{ trigger: "blur", required: true, message: "请输入单品毛重" }],
    packing_specification: {
      length: [
        { trigger: "blur", required: true, message: "请输入长" },
        { trigger: "blur", validator: validateDimension, message: "请输入有效的数字" },
      ],
      width: [
        { trigger: "blur", required: true, message: "请输入宽" },
        { trigger: "blur", validator: validateDimension, message: "请输入有效的数字" },
      ],
      height: [
        { trigger: "blur", required: true, message: "请输入高" },
        { trigger: "blur", validator: validateDimension, message: "请输入有效的数字" },
      ],
    },
  },
  countryOptions: [],
});
const { rules, formRef, currencyList, typeOptions, countryOptions } = toRefs(data);

// 其他费用
const handleOther = (type) => {
  form.value.other_fee_rmb = (
    Number(form.value.other_fee || 0) * Number(form.value.exchange_rate || 0)
  ).toFixed(2);
};

// 平台佣金
const handlePlatform = () => {
  if (form.value.commission_rate && form.value.selling_price) {
    form.value.platform_fee = (
      (Number(form.value.commission_rate) / 100) *
      Number(form.value.selling_price) *
      Number(form.value.exchange_rate)
    ).toFixed(2);
  }
};

// 选择币种
const changeCurrency = (item, type) => {
  form.value.exchange_rate = item?.exchange_rate;
  typeOptions.value[1] = item?.currency;

  nextTick(() => {
    if (form.value.other_fee_currency !== "%") {
      typeOptions.value[1] = item.currency || form.value.currency_name;
      form.value.other_fee_currency = item?.currency || form.value.currency_name;
    }
    form.value.currency_name = item?.currency;
    changePrice();
  });
  if (form.value.selling_price) {
    form.value.selling_price_rmb = (
      Number(form.value.selling_price) * Number(form.value.exchange_rate)
    ).toFixed(2);
  }
  if (form.value.selling_price && form.value.commissionRate) {
    form.value.platform_fee = (
      (Number(form.value.commissionRate) / 100) *
      Number(form.value.selling_price) *
      Number(form.value.exchange_rate)
    ).toFixed(2);
  }
  if (type !== "open") {
    handleOther();
  }
  handlePlatform();
  changeVAT();
};

// 输入价格
const changePrice = () => {
  if (form.value.exchange_rate) {
    form.value.selling_price_rmb = (
      Number(form.value.selling_price) * Number(form.value.exchange_rate)
    ).toFixed(2);
  }
  if (form.value.exchange_rate && form.value.commissionRate) {
    form.value.platform_fee = (
      (Number(form.value.commissionRate) / 100) *
      Number(form.value.selling_price) *
      Number(form.value.exchange_rate)
    ).toFixed(2);
  }
  changePercent();
  handlePlatform();
  changeVAT();
};

// 输入数字保留2位小数
const limitInput = (value, str, name) => {
  let num =
    ("" + value) // 第一步：转成字符串
      .replace(/[^\d.]/g, "") // 第二步：把不是数字，不是小数点的过滤掉
      .replace(/^0+(\d)/, "$1") // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
      .replace(/^\./, "0.") // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
      .match(/^\d*(\.?\d{0,2})/g)[0] || ""; // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数
  if (str == "form") form.value[name] = num;
  else if (str == "packing_specification") form.value.packing_specification[name] = num;
};

const changeHead = (val) => {
  const item = channel_options.find((i) => i.value == val);
  form.value.head_channel = item?.label;
  form.value.head_logistic_channel_id = "";
};
const changeTail = (val) => {
  const item = channel_options.find((i) => i.value == val);
  form.value.tail_channel = item?.label;
  form.value.tail_logistic_channel_id = "";
};

// 推荐渠道
const RecommendationLogisticsRef = ref();
const handleRecommendationChannel = (checked_type) => {
  if (
    !form.value.packing_specification.width ||
    !form.value.packing_specification.height ||
    !form.value.packing_specification.length
  ) {
    ElMessage.error("请输入包装尺寸长、宽、高");
    return;
  }
  if (!form.value.platform_id) {
    ElMessage.error("请选择平台");
    return;
  }
  if (!form.value.site_text) {
    ElMessage.error("请选择站点");
    return;
  }

  let zip_code;
  platformOptions.value.forEach((i) => {
    if (i.platform_id == form.value.platform_id) {
      i.sites.forEach((j) => {
        if (j.site_code == form.value.site_text) {
          zip_code =
            j.site_country_code == "US"
              ? "63001"
              : j.site_country_code == "AU"
              ? "2000"
              : "";
        }
      });
    }
  });
  const data = {
    sku_quantity: 1,
    width: form.value.packing_specification.width,
    length: form.value.packing_specification.length,
    height: form.value.packing_specification.height,
    delivery_mode: checked_type == "head" ? [2] : [3],
    platform_id: form.value.platform_id,
    destination_country: form.value.site_country_code,
    zip_code,
    checked_type,
    package_weight: Number(form.value.gross_weight_g),
    transport_type:
      checked_type == "head" ? form.value.head_channel_id : form.value.tail_channel_id,
    warehouse: checked_type == "tail" ? form.value.destination_warehouse_id : null,
    goods_attrs: formData.value.logistic_attr,
    goods_attrs_text: formData.value.logistic_attr_text,
    freight_calc_mode: 3,
  };
  RecommendationLogisticsRef.value.open(data);
};

// 选择后回调
const checkedLogistics = (row) => {
  if (row.checked_type == "head") {
    form.value.head_channel_id = row.transport_type;
    form.value.head_channel = row.transport_type_text;
    form.value.head_time = row.time_limit;
    form.value.head_freight = row.freight_cny;
    form.value.head_logistic_channel_id = row.channel_id;
    form.value.head_logistic_channel = row.channel_name;
    changeChannel(row.transport_type);
  } else if (row.checked_type == "tail") {
    form.value.tail_channel_id = row.transport_type;
    form.value.tail_channel = row.transport_type_text;
    form.value.tail_time = row.time_limit;
    form.value.tail_freight = row.freight_cny;
    form.value.tail_logistic_channel_id = row.channel_id;
    form.value.tail_logistic_channel = row.channel_name;
  }
};

const changePlatform = (val) => {
  form.value.platform_code = val;
  if (val == "amazon") {
    form.value.oversea_into_cost = "";
  } else {
    form.value.fba_cost = "";
  }
};

const SelectCurrencyRef = ref();
const changeSite = (item) => {
  if (item.currency_name) {
    form.value.currency_id = item.currency_id;
    SelectCurrencyRef.value.change(form.value.currency_id);
  } else {
    const find = countryOptions.value.find((i) => i.country == item.site_country_code);
    if (find) {
      form.value.currency_id = find?.base_currencys?.id;
      SelectCurrencyRef.value.change(form.value.currency_id);
    }
  }
  form.value.site_country_code = item.site_country_code;
  const findTax = VATTaxRateOptions.find((i) => i.label == item.site_country_code);
  if (findTax) {
    form.value.vat_tax = findTax?.value;
  } else {
    form.value.vat_tax = 0;
  }
};

// 选择物流渠道名称赋值
const selectChannelRef = ref();
const changeChannel = async (val, key) => {
  if (key) {
    form.value[key] = val;
  }

  if (key == "head_logistic_channel" && form.value.head_logistic_channel_id) {
    await api
      .acquireChannel({
        channel_id: form.value.head_logistic_channel_id,
      })
      .then(async (res) => {
        if (res.data.length && res.data[0].has_tax == 1 && form.value.tariff) {
          const is_confirm = await handleConfirmAndUpdate();
          if (!is_confirm) {
            form.value.tariff = "";
          }
        }
      });
  }
};

// promise 封装二次确认
const handleConfirmAndUpdate = async () => {
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm("所选头程渠道包税，请确认是否继续填写关税？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        resolve(true);
      })
      .catch(() => {
        resolve(false);
      });
  });
};

const changeChannelItem = (item, key) => {
  form.value[key] = item?.transport_type;
};

const changeTariff = () => {
  if (
    form.value.tariff &&
    form.value.tariff != "0" &&
    form.value.head_logistic_channel_id
  ) {
    api
      .acquireChannel({
        channel_id: form.value.head_logistic_channel_id,
      })
      .then((res) => {
        if (
          res.data.length &&
          res.data[0].has_tax == 1 &&
          form.value.tariff &&
          form.value.tariff != "0"
        ) {
          ElMessageBox.confirm("所选头程渠道包税，请确认是否继续填写关税？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            confirmButtonClass: "btnFalses",
            distinguishCancelAndClose: true,
          })
            .then(() => {})
            .catch(() => {
              form.value.tariff = "";
            });
        }
      });
  }
};

// 利润试算
const handleTrialProfit = async (val, checked_type) => {
  if (!val) return;
  if (
    !form.value.packing_specification.width ||
    !form.value.packing_specification.height ||
    !form.value.packing_specification.length
  ) {
    ElMessage.error("请输入包装尺寸长、宽、高");
    return;
  }
  if (!form.value.platform_id) {
    ElMessage.error("请选择平台、站点");
    return;
  }
  if (!form.value.site_text) {
    ElMessage.error("请选择平台、站点");
    return;
  }
  if (!val) {
    ElMessage.error("请选择物流渠道");
    return;
  }

  let zip_code;
  platformOptions.value.forEach((i) => {
    if (i.platform_id == form.value.platform_id) {
      i.sites.forEach((j) => {
        if (j.site_code == form.value.site_text) {
          zip_code =
            j.site_country_code == "US"
              ? "63001"
              : j.site_country_code == "AU"
              ? "2000"
              : "";
        }
      });
    }
  });

  const data = {
    sku_quantity: 1,
    width: form.value.packing_specification.width,
    length: form.value.packing_specification.length,
    height: form.value.packing_specification.height,
    delivery_mode: checked_type == "head" ? [2] : [1, 3],
    platform_id: form.value.platform_id,
    destination_country: form.value.site_country_code,
    zip_code,
    checked_type,
    package_weight: Number(form.value.gross_weight_g),
    channel_id: val,
  };

  try {
    const res = await feeTrialCalcFreight({
      ...data,
    });

    if (res.data.length == 0) {
      return ElMessage.error("暂无数据");
    }
    if (checked_type == "head") {
      form.value.head_channel_id = res.data[0].transport_type;
      form.value.head_time = res.data[0].time_limit;
      form.value.head_freight = res.data[0].freight_cny;
    } else if (type == "tail") {
      form.value.tail_channel_id = res.data[0].transport_type;
      form.value.tail_time = res.data[0].time_limit;
      form.value.tail_freight = res.data[0].freight_cny;
    }
  } catch (e) {
    throw Error(e);
  }
};

onMounted(() => {
  if (!commonStore.channelOptions) {
    commonStore.getChannelList();
  }
  getCountryOptions();
});

const getCountryOptions = async () => {
  try {
    const res = await api.getCountryList({
      pageSize: 1000,
    });
    countryOptions.value = res.data;
  } catch (e) {
    throw Error(e);
  }
};

const changePercent = () => {
  if (!form.value.selling_price_rmb) return;
  if (form.value.tariff_percent) {
    form.value.tariff = (
      (Number(form.value.selling_price_rmb) * Number(form.value.tariff_percent)) /
      100
    ).toFixed(2);
  }
};

const changePerson = (val) => {
  form.value.operation_user_id_text = val;
};

const changeVAT = (val) => {
  form.value.vat_tax_fee = (
    (Number(form.value.selling_price_rmb) * Number(form.value.vat_tax)) /
    100
  ).toFixed(2);
};

const changeCountryCurrency = (item) => {
  if (item.currency_id) {
    form.value.currency_id = item.currency_id;
    changeCurrency(form.value.currency_id);
    const findTax = VATTaxRateOptions.find((i) => i.label == item.country);
    if (findTax) {
      form.value.vat_tax = findTax?.value;
    } else {
      form.value.vat_tax = 0;
    }
  }
};

const changeProductLevel = (val) => {
  const findItem = options.value["goods.GoodsSku"]?.[0].productLevelText.find(
    (i) => i.value == val
  );
  if (findItem) {
    form.value.product_level_text = findItem.label;
  }
};

const changeDestinationWarehouse = (val) => {
  form.value.destination_warehouse_id_text = val;
};

const clearValidate = () => {
  formRef?.value?.clearValidate();
};

const validate = (callback) => {
  formRef?.value?.validate((valid) => {
    callback(valid);
  });
};

const calculateOther = (form) => {
  if (form.other_fee_currency == "%") {
    const total = (Number(form.selling_price_rmb) * Number(form.other_fee / 100)).toFixed(
      2
    );

    return total;
  } else {
    const total = (Number(form.other_fee || 0) * Number(form.exchange_rate || 0)).toFixed(
      2
    );
    return total;
  }
};

defineExpose({ validate, clearValidate, changeCurrency });
</script>
<style lang="scss" scoped>
.input-select {
  display: flex;

  .el-input-group__prepend,
  .el-input__wrapper {
    flex: auto;
  }

  .el-input-group__prepend {
    padding: 0;
    background: #fff;
  }

  .el-input-group__append {
    width: 64px;
  }
}

.box-card-style {
  background: var(--base-table-header-bg-color);
  border: none;
}

.size-box {
  display: flex;
  justify-content: flex-start;

  .size-unit {
    width: 170px;
    height: 32px;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid var(--base-border-color);
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
    background-color: var(--base-home-time-color);
    border-left: none;
  }
}

.suffix-unit {
  border: 1px solid var(--base-border-color) !important;
  background-color: var(--base-home-time-color) !important;
  color: var(--base-text-color) !important;
}

:deep(.el-input-group__append, .el-input-group__prepend) {
  background-color: #fafafa;
}

:deep(input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button) {
  -webkit-appearance: none;
  margin: 0;
}

:deep(input[type="number"]) {
  -moz-appearance: textfield;
}
</style>
<style lang="scss">
.radius-left-0 {
  .el-input__wrapper {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
  }
}

.radius-right-0 {
  .el-input__wrapper {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
  }
}
</style>
